<template>
  <div class="course-management">
    <div class="header">
      <h1>课程发布系统</h1>
    </div>

    <div class="content">
      <!-- 课程信息表单 -->
      <el-card class="form-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <span>课程基本信息</span>
          </div>
        </template>

        <el-form
            ref="formRef"
            :model="course"
            label-width="150px"
            class="demo-dynamic"
        >
          <el-form-item
              prop="name"
              label="课程名称"
              class="form-item"
          >
            <el-input v-model="course.courseName"
                      placeholder="请输入课程名称"
                      clearable
                      size="large"
                      class="form-input"/>
          </el-form-item>
          <el-form-item
              prop="session"
              label="课程简介"
              class="form-item"
          >
            <el-input v-model="course.courseDesc"
                      placeholder="请输入课程简介"
                      clearable
                      size="large"
                      type="textarea"
                      class="form-input"/>
          </el-form-item>
          <el-form-item
              prop="session"
              label="开放时间"
              class="form-item"
          >
            <el-input v-model="course.openDuration"
                      placeholder="请输入开放时间（单位：天）"
                      clearable
                      size="large"
                      class="form-input"/>
          </el-form-item>
          <el-form-item
              prop="session"
              label="开始日期"
              class="form-item"
          >
            <el-date-picker
                v-model="course.startTime"
                type="datetime"
                placeholder="请选择开始日期"
                format="YYYY/MM/DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>

          <el-form-item class="form-actions">
            <el-button @click="changeTableFlag" type="success" icon="Plus">
              {{ tableFlag ? '隐藏学习资源' : '添加学习资源' }}
            </el-button>
            <el-button @click="insertCourse" type="primary" icon="Check" :disabled="!canCreateCourse">
              创建课程
            </el-button>
            <el-button @click="resetForm" type="info" icon="Refresh">
              重置表单
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 资源选择区域 -->
      <el-card v-if="tableFlag" class="resource-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <span>选择学习资源</span>
            <el-button type="text" @click="refreshResources" :icon="Refresh" :loading="loading">
              刷新
            </el-button>
          </div>
        </template>

        <!-- 搜索区域 -->
        <div class="search-container">
          <el-input
              v-model="searchKeyword"
              placeholder="请输入资源名称进行搜索"
              clearable
              style="width: 300px;"
              @clear="handleSearch"
              @keyup.enter="handleSearch"
              @input="handleSearch"
          >
            <template #append>
              <el-button @click="handleSearch" :icon="Search">搜索</el-button>
            </template>
          </el-input>

          <div class="selected-info" v-if="selectedResources.length > 0">
            <el-tag type="success" size="large">
              已选择 {{ selectedResources.length }} 个资源
            </el-tag>
            <el-button @click="clearSelection" type="text" size="small">
              清空选择
            </el-button>
          </div>
        </div>

        <!-- 资源表格 -->
        <el-table
            ref="resourceTableRef"
            :data="paginatedResources"
            border
            style="width: 100%"
            highlight-current-row
            v-loading="loading"
            row-key="id"
            @selection-change="handleSelectionChange"
        >
          <el-table-column
              type="selection"
              width="55"
              :reserve-selection="true" />
          <el-table-column prop="id" label="编号" width="80" align="center" />
          <el-table-column prop="resourceName" label="资源名" width="180" show-overflow-tooltip />
          <el-table-column prop="isDocument" label="类型" width="100" align="center">
            <template #default="scope">
              <el-tag :type="scope.row.isDocument ? 'warning' : 'success'">
                {{ scope.row.isDocument ? '视频' : '文档' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="resourceTotalDuration" label="时长" width="100" align="center">
            <template #default="scope">
              {{ formatDuration(scope.row.resourceTotalDuration) }}
            </template>
          </el-table-column>
          <el-table-column prop="resourceUrl" label="地址" show-overflow-tooltip />
          <el-table-column prop="tagId" label="标签" width="120" align="center">
            <template #default="scope">
              <el-tag v-if="getTagName(scope.row.tagId)" type="info">
                {{ getTagName(scope.row.tagId) }}
              </el-tag>
              <span v-else class="no-tag">无标签</span>
            </template>
          </el-table-column>
          <el-table-column prop="resourceDesc" label="说明" show-overflow-tooltip />
          <!-- 添加操作列 -->
          <el-table-column label="操作" width="100" align="center" fixed="right">
            <template #default="scope">
              <el-button
                  type="primary"
                  size="small"
                  @click="showResourceDetail(scope.row)"
                  plain
              >
                查看
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页组件 -->
        <div class="pagination-container" v-if="filteredResources.length > 0">
          <el-pagination
              background
              layout="total, sizes, prev, pager, next, jumper"
              :total="filteredResources.length"
              :page-size="pagination.pageSize"
              :current-page="pagination.pageNum"
              :page-sizes="[10, 20, 50, 100]"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
          />
        </div>

        <!-- 空状态 -->
        <div class="empty-state" v-if="!loading && filteredResources.length === 0">
          <el-empty :description="searchKeyword ? '暂无匹配的资源数据' : '暂无资源数据'">
            <el-button type="primary" @click="refreshResources">刷新数据</el-button>
          </el-empty>
        </div>
      </el-card>
    </div>

    <!-- 资源详情弹窗 -->
    <el-dialog
        v-model="dialogVisible"
        title="资源详情"
        width="600px"
        :before-close="handleClose"
    >
      <div class="resource-detail">
        <el-descriptions
            :column="1"
            border
            class="detail-descriptions"
        >
          <el-descriptions-item label="资源编号">{{ currentResource?.id }}</el-descriptions-item>
          <el-descriptions-item label="资源名称">{{ currentResource?.resourceName }}</el-descriptions-item>
          <el-descriptions-item label="资源类型">
            <el-tag :type="currentResource?.isDocument ? 'warning' : 'success'">
              {{ currentResource?.isDocument ? '视频' : '文档' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="时长">{{ currentResource && formatDuration(currentResource.resourceTotalDuration) }}</el-descriptions-item>
          <el-descriptions-item label="标签">{{ currentResource && getTagName(currentResource.tagId) || '无标签' }}</el-descriptions-item>
          <el-descriptions-item label="资源地址">
            <el-input
                v-if="currentResource"
                v-model="currentResource.resourceUrl"
                readonly
                class="url-input"
            />
          </el-descriptions-item>
          <el-descriptions-item label="资源说明" :span="2">
            <div class="description-content" v-if="currentResource">
              {{ currentResource.resourceDesc || '暂无说明' }}
            </div>
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 资源详情弹窗 - 增加编辑功能 -->
    <el-dialog
        v-model="dialogVisible"
        title="资源详情"
        width="600px"
        :before-close="handleClose"
    >
      <div class="resource-detail">
        <el-descriptions
            :column="1"
            border
            class="detail-descriptions"
        >
          <el-descriptions-item label="资源编号">{{ currentResource?.id }}</el-descriptions-item>
          <el-descriptions-item label="资源名称">
            <template v-if="!isEditMode">
              {{ currentResource?.resourceName }}
            </template>
            <template v-else>
              <el-input v-model="editResource.resourceName" placeholder="请输入资源名称" />
            </template>
          </el-descriptions-item>
          <el-descriptions-item label="资源类型">
            <template v-if="!isEditMode">
              <el-tag :type="currentResource?.isDocument ? 'warning' : 'success'">
                {{ currentResource?.isDocument ? '视频' : '文档' }}
              </el-tag>
            </template>
            <template v-else>
              <el-radio-group v-model="editResource.isDocument">
                <el-radio :label="true">视频</el-radio>
                <el-radio :label="false">文档</el-radio>
              </el-radio-group>
            </template>
          </el-descriptions-item>
          <el-descriptions-item label="时长">
            <template v-if="!isEditMode">
              {{ currentResource && formatDuration(currentResource.resourceTotalDuration) }}
            </template>
            <template v-else>
              <el-input-number
                  v-model="editResource.resourceTotalDuration"
                  :min="0"
                  placeholder="秒"
                  style="width: 100%;"
              />
            </template>
          </el-descriptions-item>
          <el-descriptions-item label="标签">
            <template v-if="!isEditMode">
              {{ currentResource && getTagName(currentResource.tagId) || '无标签' }}
            </template>
            <template v-else>
              <el-select v-model="editResource.tagId" placeholder="请选择标签">
<!--                <el-option label="无标签" :value="0" />-->
                <el-option
                    v-for="tag in allTag"
                    :key="tag.id"
                    :label="tag.tagName"
                    :value="tag.id"
                />
              </el-select>
            </template>
          </el-descriptions-item>
          <el-descriptions-item label="资源地址">
            <template v-if="!isEditMode">
              <el-input
                  v-if="currentResource"
                  v-model="currentResource.resourceUrl"
                  readonly
                  class="url-input"
              />
            </template>
            <template v-else>
              <el-input v-model="editResource.resourceUrl" placeholder="请输入资源地址" />
            </template>
          </el-descriptions-item>
          <el-descriptions-item label="资源说明" :span="2">
            <template v-if="!isEditMode">
              <div class="description-content" v-if="currentResource">
                {{ currentResource.resourceDesc || '暂无说明' }}
              </div>
            </template>
            <template v-else>
              <el-input
                  v-model="editResource.resourceDesc"
                  type="textarea"
                  :rows="3"
                  placeholder="请输入资源说明"
              />
            </template>
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button v-if="!isEditMode" @click="enterEditMode">编辑</el-button>
          <el-button v-if="isEditMode" @click="cancelEdit">取消</el-button>
          <el-button v-if="isEditMode" type="primary" @click="saveResource">保存</el-button>
          <el-button @click="dialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted, computed, nextTick } from 'vue'
import { ElMessage, type FormInstance, type ElTable } from 'element-plus'
import { Search, Refresh, Plus, Check } from '@element-plus/icons-vue'
import request from "@/utils/request.ts"

// 定义标签类型
interface Tag {
  id: number
  tagName: string
  // 可以根据实际接口返回的字段添加其他属性
}

// 定义课程类型
interface Course {
  courseName: string | null
  courseDesc: string | null
  openDuration: number | null
  startTime: string | null
  endTime: string | null
  stop:boolean | null
  createTime: string | null
  creatAdminId: number | null
  resourceIds?: number[]
}

// 定义资源类型
interface Resource {
  id: number
  resourceName: string
  isDocument: boolean
  resourceTotalDuration: number
  resourceUrl: string
  tagId: number
  resourceDesc: string
}

// 响应式数据
const tableFlag = ref(false)
const loading = ref(false)
const searchKeyword = ref('')
const formRef = ref<FormInstance>()
const allTag = ref<Tag[]>([])
const resourceTableRef = ref<InstanceType<typeof ElTable>>()
const selectedResources = ref<Resource[]>([])

// 弹窗相关状态
const dialogVisible = ref(false)
const currentResource = ref<Resource | null>(null)
const isEditMode = ref(false)
const editResource = ref<Resource>({
  id: 0,
  resourceName: '',
  isDocument: false,
  resourceTotalDuration: 0,
  resourceUrl: '',
  tagId: 0,
  resourceDesc: ''
})


// 所有资源数据
const allResources = ref<Resource[]>([])

// 前端分页配置
const pagination = reactive({
  pageNum: 1,
  pageSize: 10
})

// 课程数据
const course = ref<Course>({
  courseName: null,
  courseDesc: null,
  openDuration: null,
  startTime: null,
  endTime: null,
  createTime: null,
  creatAdminId: null,
  stop:false,
  resourceIds: []
})

// 计算属性：是否可以创建课程（必须选择至少一个资源）
const canCreateCourse = computed(() => {
  return selectedResources.value.length > 0 &&
      course.value.courseName?.trim() &&
      course.value.courseDesc?.trim() &&
      course.value.openDuration &&
      course.value.startTime
})

// 计算属性：过滤后的资源（前端搜索）
const filteredResources = computed(() => {
  if (!searchKeyword.value.trim()) {
    return allResources.value
  }

  const keyword = searchKeyword.value.toLowerCase().trim()
  return allResources.value.filter(resource =>
      resource.resourceName.toLowerCase().includes(keyword) ||
      (resource.resourceDesc && resource.resourceDesc.toLowerCase().includes(keyword))
  )
})

// 计算属性：分页后的资源
const paginatedResources = computed(() => {
  const start = (pagination.pageNum - 1) * pagination.pageSize
  const end = start + pagination.pageSize
  return filteredResources.value.slice(start, end)
})

// 根据标签ID获取标签名称
const getTagName = (tagId: number): string => {
  if (!tagId) return ''
  const tag = allTag.value.find(tag => tag.id === tagId)
  return tag ? tag.tagName : ''
}

// 生命周期
onMounted(() => {
  selectAllTag();
})

// 获取所有标签
const selectAllTag = async () => {
  try {
    const res = await request.get("/trainingTag/list")
    if (res.data && res.data.trainingTags) {
      allTag.value = res.data.trainingTags
      console.log('获取到的所有标签数据:', allTag.value)
    }
  } catch (error) {
    console.error('获取标签列表失败:', error)
    ElMessage.error('获取标签列表失败')
  }
}

// 获取所有资源列表
const selectAllResource = async () => {
  loading.value = true
  try {
    const res = await request.get("/trainingResource/allList")

    if (res.data && res.data.resourceList) {
      allResources.value = res.data.resourceList

      // 重置分页到第一页
      pagination.pageNum = 1

      // 数据加载完成后，恢复之前的选择状态
      nextTick(() => {
        restoreSelection()
      })
    } else {
      ElMessage.warning('数据格式异常，请检查后端接口')
    }
  } catch (error) {
    ElMessage.error('获取资源列表失败')
  } finally {
    loading.value = false
  }
}

// 恢复选择状态
const restoreSelection = () => {
  if (resourceTableRef.value && selectedResources.value.length > 0) {
    const selectedIds = new Set(selectedResources.value.map(item => item.id))
    paginatedResources.value.forEach(row => {
      if (selectedIds.has(row.id)) {
        nextTick(() => {
          resourceTableRef.value!.toggleRowSelection(row, true)
        })
      }
    })
  }
}

// 搜索处理（前端搜索）
const handleSearch = () => {
  pagination.pageNum = 1 // 搜索时回到第一页
  // 搜索后恢复选择状态
  nextTick(() => {
    restoreSelection()
  })
}

// 刷新资源列表
const refreshResources = () => {
  selectAllResource()
}

// 分页事件处理（前端分页）
const handleCurrentChange = (currentPage: number) => {
  pagination.pageNum = currentPage
  // 分页后恢复选择状态
  nextTick(() => {
    restoreSelection()
  })
}

const handleSizeChange = (pageSize: number) => {
  pagination.pageSize = pageSize
  pagination.pageNum = 1 // 切换每页大小时回到第一页
  // 分页大小改变后恢复选择状态
  nextTick(() => {
    restoreSelection()
  })
}

// 表格显示切换
const changeTableFlag = () => {
  tableFlag.value = !tableFlag.value
  if (tableFlag.value && allResources.value.length === 0) {
    selectAllResource()
  }
}

// 选择资源处理
const handleSelectionChange = (selection: Resource[]) => {
  // 更新已选择的资源
  const selectedIds = new Set(selection.map(item => item.id))

  // 合并之前的选择和当前的选择，避免重复
  const allSelected = [...selectedResources.value.filter(item => !selectedIds.has(item.id)), ...selection]

  selectedResources.value = allSelected
  course.value.resourceIds = allSelected.map(item => item.id)
  console.log('已选择的资源ID:', course.value.resourceIds)
}

// 清空选择
const clearSelection = () => {
  selectedResources.value = []
  course.value.resourceIds = []
  if (resourceTableRef.value) {
    resourceTableRef.value.clearSelection()
  }
  ElMessage.info('已清空资源选择')
}

// 格式化时长显示
const formatDuration = (seconds: number) => {
  if (!seconds) return '0秒'
  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  const secs = seconds % 60

  if (hours > 0) {
    return `${hours}时${minutes}分${secs}秒`
  } else if (minutes > 0) {
    return `${minutes}分${secs}秒`
  } else {
    return `${secs}秒`
  }
}

// 重置表单
const resetForm = () => {
  course.value = {
    courseName: null,
    courseDesc: null,
    openDuration: null,
    stop:null,
    startTime: null,
    endTime: null,
    createTime: null,
    creatAdminId: null,
    resourceIds: []
  }
  selectedResources.value = []
  if (resourceTableRef.value) {
    resourceTableRef.value.clearSelection()
  }
  ElMessage.success('表单已重置')
}

// 创建课程
const insertCourse = async () => {
  // 表单验证
  if (!course.value.courseName?.trim()) {
    ElMessage.warning('请输入课程名称')
    return
  }

  if (!course.value.courseDesc?.trim()) {
    ElMessage.warning('请输入课程简介')
    return
  }

  if (!course.value.openDuration) {
    ElMessage.warning('请输入开放时间')
    return
  }

  if (!course.value.startTime) {
    ElMessage.warning('请选择开始日期')
    return
  }

  // 检查是否选择了资源
  if (!course.value.resourceIds || course.value.resourceIds.length === 0) {
    ElMessage.warning('请至少选择一个学习资源')
    return
  }

  // 转换数据类型
  course.value.openDuration = course.value.openDuration ? Number(course.value.openDuration) : null

  // 设置创建时间和创建者ID
  course.value.createTime = new Date().toISOString().slice(0, 19).replace('T', ' ')


  // 从 localStorage 获取管理员ID
  const adminData = localStorage.getItem('admin')
  if (adminData) {
    try {
      const admin = JSON.parse(adminData)
      course.value.creatAdminId = admin.id || null
    } catch (error) {
      console.error('解析管理员数据失败:', error)
      course.value.creatAdminId = null
    }
  } else {
    course.value.creatAdminId = null
  }

  // 计算结束时间：开始时间 + 开放天数
  if (course.value.startTime && course.value.openDuration) {
    const startDate = new Date(course.value.startTime)
    const endTime = new Date(startDate)
    endTime.setDate(startDate.getDate() + (course.value.openDuration || 0))
    course.value.endTime = endTime.toISOString().slice(0, 19).replace('T', ' ')
  } else {
    course.value.endTime = null
  }

  console.log('完整课程数据:', course.value)

  try {
    const res = await request.post('/course/save', course.value)
    console.log('创建课程响应:', res.data)

    if (res.data.code === 200) {
      ElMessage.success('课程创建成功')
      resetForm()
      tableFlag.value = false
    } else {
      ElMessage.error(res.data.msg || '课程创建失败')
    }
  } catch (error: any) {
    console.error('创建课程失败:', error)
    ElMessage.error(error.response?.data?.msg || '课程创建失败')
  }
}

// 显示资源详情
const showResourceDetail = (resource: Resource) => {
  currentResource.value = { ...resource }
  dialogVisible.value = true
  isEditMode.value = false // 默认显示查看模式
}

// 进入编辑模式
const enterEditMode = () => {
  if (currentResource.value) {
    // 复制当前资源数据到编辑对象，确保所有必要字段都被复制
    editResource.value = {
      ...currentResource.value,
      // 确保isDocument是布尔值
      isDocument: currentResource.value.isDocument === true
    };
    isEditMode.value = true;
  }
}

// 取消编辑
const cancelEdit = () => {
  isEditMode.value = false
  // 清空编辑数据
  editResource.value = {
    id: 0,
    resourceName: '',
    isDocument: false,
    resourceTotalDuration: 0,
    resourceUrl: '',
    tagId: 0,
    resourceDesc: ''
  }
}

// 保存资源修改
const saveResource = async () => {
  // 表单验证
  if (!editResource.value.resourceName.trim()) {
    ElMessage.warning('请输入资源名称')
    return
  }

  if (!editResource.value.resourceUrl.trim()) {
    ElMessage.warning('请输入资源地址')
    return
  }

  try {
    // 调用API保存修改
    const res = await request.post('/trainingResource/update', editResource.value)

    if (res.data && res.data.code === 200) {
      ElMessage.success('资源更新成功')
      // 更新当前显示的数据
      currentResource.value = { ...editResource.value }
      // 刷新资源列表
      selectAllResource()
      // 退出编辑模式
      isEditMode.value = false
    } else {
      ElMessage.error(res.data?.msg || '资源更新失败')
    }
  } catch (error: any) {
    console.error('保存资源失败:', error)
    ElMessage.error(error.response?.data?.msg || '保存资源失败，请稍后重试')
  }
}


// 关闭弹窗处理 - 合并功能，保留完整的清理逻辑
const handleClose = () => {
  dialogVisible.value = false
  isEditMode.value = false // 确保关闭时退出编辑模式
  // 延迟清空数据，避免闪烁
  setTimeout(() => {
    currentResource.value = null
    editResource.value = {
      id: 0,
      resourceName: '',
      isDocument: false,
      resourceTotalDuration: 0,
      resourceUrl: '',
      tagId: 0,
      resourceDesc: ''
    }
  }, 300)
  }
</script>

<style scoped>
.course-management {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.header {
  margin-bottom: 20px;
  text-align: center;
}

.header h1 {
  color: #303133;
  margin: 0;
  font-size: 28px;
  font-weight: 600;
}

.content {
  max-width: 1200px;
  margin: 0 auto;
}

.form-card, .resource-card {
  margin-bottom: 20px;
  border-radius: 8px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
  font-size: 16px;
}

.form-item {
  margin-bottom: 22px;
}

.form-input {
  width: 400px;
}

.form-actions {
  margin-top: 30px;
  text-align: center;
}

.search-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 0 10px;
}

.selected-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.empty-state {
  padding: 40px 0;
}

.no-tag {
  color: #909399;
  font-size: 12px;
}

:deep(.el-card__header) {
  background-color: #fafafa;
  border-bottom: 1px solid #e4e7ed;
}

:deep(.el-table) {
  border-radius: 4px;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  font-weight: 600;
}

/* 详情弹窗样式 */
.resource-detail {
  padding: 10px 0;
}

.detail-descriptions {
  margin-bottom: 10px;
}

.url-input {
  width: 100%;
}

.description-content {
  padding: 10px;
  min-height: 60px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  white-space: pre-wrap;
  word-break: break-word;
  background-color: #fafafa;
}
/* 详情弹窗样式 */
.resource-detail {
  padding: 10px 0;
}

.detail-descriptions {
  margin-bottom: 10px;
}

.url-input {
  width: 100%;
}

.description-content {
  padding: 10px;
  min-height: 60px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  white-space: pre-wrap;
  word-break: break-word;
  background-color: #fafafa;
}
</style>
